package com.heima.user.service.impl;

import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.UpdateArticleMess;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.UserRelationService;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Auther: Tangguo
 * @Date: 2023-06-22  08:58
 */
@Service
public class UserRelationServiceImpl implements UserRelationService {
    @Autowired
    private CacheService cacheService;

    /**
     * 关注与取消关注
     * @param dto :
     * @return ResponseResult
     */
    @Override
    public ResponseResult userFollow(UserRelationDto dto) {
        //1.参数校验
        if(dto==null||dto.getAuthorId()==null||(dto.getOperation()<0||dto.getOperation()>1)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.数据处理
        //2.1判断用户当前是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN,"当前未登录，请登录后再操作");
        }
        //2.2拿到当用户id
        Integer userId = user.getId();

        //3.业务操作  0  关注   1  取消
        //获取作者id
        Integer authorId=dto.getAuthorId();
        if(dto.getOperation()==0) {
            //3.1从用户的角度出发：—— 我的关注
            cacheService.zAdd(BehaviorConstants.APUSER_FOLLOW_RELATION+userId,authorId.toString(),System.currentTimeMillis());
            //3.2从作者的角度出发： —— 我的粉丝
            cacheService.zAdd(BehaviorConstants.APUSER_FANS_RELATION+authorId,userId.toString(),System.currentTimeMillis());

        }else {
            //取消
            cacheService.zRemove(BehaviorConstants.APUSER_FOLLOW_RELATION + userId, authorId.toString());
            cacheService.zRemove(BehaviorConstants.APUSER_FANS_RELATION + authorId, userId.toString());

        }
        //4.返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
